package xq.gwt.ui.crud;

import xq.gwt.mvc.model.BooleanPropertyModel;
import xq.gwt.mvc.model.CommandModel;
import xq.gwt.mvc.model.EntityChangedEvent;
import xq.gwt.mvc.model.EntityChangedListener;
import xq.gwt.mvc.model.PersistableEntityModel;
import xq.gwt.ui.crud.localization.CrudDictionary;


public class SaveEntityCommand implements CommandModel, EntityChangedListener{		
	private static final long serialVersionUID = -4082842118663912338L;
	private BooleanPropertyModel enabled = new BooleanPropertyModel();
	private PersistableEntityModel persistableEntity;
	private EntityEditorModel editorModel;
	private String feedBack;
	

	public SaveEntityCommand(EntityEditorModel editorModel){
		this.editorModel = editorModel;
		enabled = new BooleanPropertyModel();
		updateEnabled();
	}
	
	public SaveEntityCommand(PersistableEntityModel persistableEntity, EntityEditorModel editorModel){
		this.editorModel = editorModel;
		enabled = new BooleanPropertyModel();
		setEntity(persistableEntity);
		
	}
	
	public void setEntity(PersistableEntityModel persistableEntity){
		if(this.persistableEntity != null){
			this.persistableEntity.removeEntityChangedListener(this);
		}
		this.persistableEntity = persistableEntity;
		if(persistableEntity != null)
			this.persistableEntity.addEntityChangedListener(this);
		updateEnabled();
	}
	
	private void updateEnabled(){
		if(persistableEntity == null){
			enabled.setValue(false);
		}
		else{
			enabled.setValue(persistableEntity.isValid());
		}
		
	}
	
	@Override
	public void execute() throws Exception {
		feedBack = null;		
		PersistableEntityModel dtoEntity = persistableEntity.copy();
		PersistEntityCommand persist = new PersistEntityCommand(dtoEntity, editorModel);
		if(editorModel.getBeforePersistListener() == null){
			persist.execute();
		} else {			
			editorModel.getBeforePersistListener().onBeforePersist(dtoEntity, persist);			
		}
		
	}
	
	
	@Override
	public String getCaption() {			
		return CrudDictionary.Constants().save_caption();
	}

	@Override
	public String getName() {			
		return "Save";
	}

	@Override
	public BooleanPropertyModel isEnabled() {		
		return enabled;
	}

	@Override
	public String getFeedback() {		
		return feedBack;
	}

	@Override
	public void entityChanged(EntityChangedEvent event) {
		updateEnabled();
		
	}
	
}
